package com.vilynn.learning.new2.question;

/**
 * A
 *
 * @author Weilin Wang
 * @since 2020/4/23
 */

/**
 * 给定一棵二叉树，你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
 *
 *  
 *
 * 示例 :
 * 给定二叉树
 *
 *           1
 *          / \
 *         2   3
 *        / \
 *       4   5
 * 返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
 *
 *  
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/diameter-of-binary-tree
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 *
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class BinaryTree {
    static int result = 0;

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(1);
        root.right = new TreeNode(1);

        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(1);

        root.right.left = new TreeNode(1);
        root.right.right = new TreeNode(1);

        root.left.left.right = new TreeNode(1);
        root.left.left.right.right = new TreeNode(1);

        System.out.println(diameterOfBinaryTree(root));
    }

    public static int diameterOfBinaryTree(TreeNode root) {
        diameter(root);
        return result;
    }

    private static int diameter(TreeNode node) {
        if (node == null) {
            return 0;
        }
        int l = diameter(node.left);
        int r = diameter(node.right);
        result = Math.max(result, l + r);
        return Math.max(l, r) + 1;
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }
}
